<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate">
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Expires" content="0">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI终端</title>
    <script src="../js/config.js"></script>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .container {
            display: flex;
            gap: 20px;
        }
        .panel {
            flex: 1;
            background: white;
            border-radius: 8px;
            padding: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        .controls {
            margin-bottom: 20px;
            padding: 15px;
            background-color: #f8f9fa;
            border-radius: 5px;
        }
        .messages {
            height: 400px;
            overflow-y: auto;
            border: 1px solid #ddd;
            padding: 15px;
            margin-bottom: 20px;
            border-radius: 5px;
            background-color: #fff;
        }
        .message {
            margin-bottom: 15px;
            padding: 10px;
            border-radius: 5px;
            word-wrap: break-word;
        }
        .user {
            background-color: #e3f2fd;
            border-left: 4px solid #2196f3;
        }
        .assistant {
            background-color: #f3e5f5;
            border-left: 4px solid #9c27b0;
        }
        .system {
            background-color: #e8f5e8;
            border-left: 4px solid #4caf50;
        }
        .input-area {
            display: flex;
            margin-top: 10px;
            gap: 10px;
        }
        .input-area input, .input-area textarea {
            flex: 1;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        button {
            padding: 10px 15px;
            cursor: pointer;
            background-color: #2196f3;
            color: white;
            border: none;
            border-radius: 4px;
            transition: background-color 0.3s;
        }
        button:hover {
            background-color: #0b7dda;
        }
        button:disabled {
            background-color: #ccc;
            cursor: not-allowed;
        }
        .screenshot-container {
            text-align: center;
            margin-bottom: 20px;
        }
        .image-preview {
            max-width: 100%;
            max-height: 300px;
            margin: 10px 0;
            border-radius: 5px;
        }
        .action-buttons {
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
            margin: 15px 0;
        }
        .action-buttons button {
            flex: 1;
            min-width: 120px;
        }
        .detection-info {
            margin-top: 20px;
            padding: 15px;
            background-color: #e3f2fd;
            border-radius: 5px;
        }
        .loading {
            display: none;
            color: #2196f3;
            font-style: italic;
        }
        h1, h2, h3 {
            color: #333;
        }
        .grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
        }
        @media (max-width: 768px) {
            .container {
                flex-direction: column;
            }
            .grid {
                grid-template-columns: 1fr;
            }
        }
        .back-link {
            display: inline-block;
            margin-bottom: 20px;
            padding: 10px 15px;
            background-color: #6c757d;
            color: white;
            text-decoration: none;
            border-radius: 5px;
        }
    </style>
</head>
<body>
    <h1>AI终端</h1>
    <a href="../index.html" class="back-link">← 返回主页</a>
    
    <div class="container">
        <div class="panel">
            <h2>屏幕截图与图像分析</h2>
            
            <div class="controls">
                <div class="screenshot-container">
                    <div id="imagePreviewContainer" style="display:none;">
                        <h3>截图预览:</h3>
                        <img id="imagePreview" class="image-preview" alt="截图预览">
                    </div>
                </div>
                
                <div class="action-buttons">
                    <button id="captureScreenBtn">截取屏幕</button>
                    <button id="analyzeBtn" disabled>分析图像</button>
                    <button id="resetBtn">重置</button>
                </div>
                
                <div id="loadingIndicator" class="loading">正在处理中...</div>
            </div>
            
            <div class="detection-info" id="detectionInfo" style="display:none;">
                <h3>检测结果:</h3>
                <div id="detectionResults"></div>
            </div>
        </div>
        
        <div class="panel">
            <h2>AI交互终端</h2>
            
            <div class="messages" id="messages">
                <div class="message system">
                    <strong>系统 [初始化]</strong><br>
                    欢迎使用AI终端！您可以发送消息与AI交互，或使用屏幕截图功能进行图像分析。
                </div>
            </div>
            
            <div class="input-area">
                <textarea id="messageInput" placeholder="输入您的消息..." rows="3"></textarea>
                <button id="sendBtn">发送</button>
            </div>
            
            <div class="action-buttons">
                <button id="analyzeImageBtn" disabled>分析当前截图</button>
                <button id="clickDetectedBtn" disabled>点击检测目标</button>
            </div>
        </div>
    </div>

    <script>
        // 计时工具函数
        function withTiming(operationName, asyncFn) {
            return async function(...args) {
                const startTime = performance.now();
                console.log(`开始执行 ${operationName}...`);
                addMessage(`开始执行 ${operationName}...`, 'system');
                
                try {
                    const result = await asyncFn.apply(this, args);
                    const endTime = performance.now();
                    const duration = endTime - startTime;
                    console.log(`${operationName} 执行完成，耗时: ${duration.toFixed(2)}ms`);
                    addMessage(`${operationName} 执行完成，耗时: ${duration.toFixed(2)}ms`, 'system');
                    return result;
                } catch (error) {
                    const endTime = performance.now();
                    const duration = endTime - startTime;
                    console.error(`${operationName} 执行失败，耗时: ${duration.toFixed(2)}ms，错误: ${error.message}`);
                    addMessage(`${operationName} 执行失败，耗时: ${duration.toFixed(2)}ms，错误: ${error.message}`, 'system');
                    throw error;
                }
            };
        }
        
        // 全局变量
        let capturedImage = null;
        let detectionData = null;
        const imagePreview = document.getElementById('imagePreview');
        const BASE_URL = APP_CONFIG.BASE_URL;
        
        // 对话历史记录
        let conversationHistory = [
            {
                role: "system",
                content: "你是一个智能助手，能够帮助用户解决问题和提供信息。你还可以调用工具来执行特定操作。\n" +
                         "可用工具列表：\n" +
                         "1. capture_screen - 截取屏幕截图\n" +
                         "2. analyze_image_with_yolo - 使用YOLO进行通用目标检测\n" +
                         "3. analyze_image_with_groundingdino - 使用GroundingDINO进行特定目标检测，需要提供prompt参数\n" +
                         "4. click_detected_object - 点击检测到的对象\n\n" +
                         "当需要执行操作时，请使用工具调用格式：\n" +
                         "<tool_call>{\"name\": \"capture_screen\"}</tool_call>\n" +
                         "<tool_call>{\"name\": \"analyze_image_with_yolo\"}</tool_call>\n" +
                         "<tool_call>{\"name\": \"analyze_image_with_groundingdino\", \"arguments\": {\"prompt\": \"要检测目标的英语描述,结尾要带个.符号,比如cat.dog.\"}}</tool_call>\n" +
                         "<tool_call>{\"name\": \"click_detected_object\", \"arguments\": {\"object_name\": \"指定对象名称\"}}</tool_call>\n\n" +
                         "请根据用户请求决定是否需要调用工具，并在调用后解释结果。当用户提到特定物体时（如'查找红色按钮'），使用GroundingDINO并提取目标描述；当需要通用物体检测时（如'分析图像中的物体'），使用YOLO。"
            }
        ];
        
        // DOM元素
        const captureScreenBtn = document.getElementById('captureScreenBtn');
        const analyzeBtn = document.getElementById('analyzeBtn');
        const resetBtn = document.getElementById('resetBtn');
        const sendBtn = document.getElementById('sendBtn');
        const analyzeImageBtn = document.getElementById('analyzeImageBtn');
        const clickDetectedBtn = document.getElementById('clickDetectedBtn');
        const messageInput = document.getElementById('messageInput');
        const messagesDiv = document.getElementById('messages');
        const loadingIndicator = document.getElementById('loadingIndicator');
        const imagePreviewContainer = document.getElementById('imagePreviewContainer');
        const detectionInfo = document.getElementById('detectionInfo');
        const detectionResults = document.getElementById('detectionResults');
        
        // 事件监听器
        captureScreenBtn.addEventListener('click', captureScreen);
        analyzeBtn.addEventListener('click', analyzeImageWithYOLO);
        resetBtn.addEventListener('click', resetAll);
        sendBtn.addEventListener('click', sendMessage);
        analyzeImageBtn.addEventListener('click', analyzeCurrentImage);
        clickDetectedBtn.addEventListener('click', clickDetectedObject);
        messageInput.addEventListener('keypress', function(e) {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                sendMessage();
            }
        });
        
        // 截取屏幕 - 添加计时
        async function captureScreen() {
            const startTime = performance.now();
            console.log('开始截取屏幕...');
            addMessage('正在截取屏幕...', 'system');
            
            try {
                // 使用配置文件中的 BASE_URL
                const response = await fetch(`${BASE_URL}/mouse/screenshot`);
                
                const proxyResponseTime = performance.now();
                const proxyDuration = proxyResponseTime - startTime;
                console.log(`截图服务响应时间: ${proxyDuration.toFixed(2)}ms`);
                
                const screenshotResult = await response.json();
                const resultParseTime = performance.now();
                const resultParseDuration = resultParseTime - startTime;
                console.log(`截图服务结果解析时间: ${resultParseDuration.toFixed(2)}ms`);
                
                if (screenshotResult.status === 'success') {
                    // 显示截图
                    capturedImage = 'data:image/png;base64,' + screenshotResult.image;
                    imagePreview.src = capturedImage;
                    imagePreviewContainer.style.display = 'block';
                    analyzeBtn.disabled = false;
                    
                    const endTime = performance.now();
                    const duration = endTime - startTime;
                    console.log(`屏幕截图完成，总耗时: ${duration.toFixed(2)}ms`);
                    addMessage(`屏幕截图完成，总耗时: ${duration.toFixed(2)}ms`, 'system');
                } else {
                    const endTime = performance.now();
                    const duration = endTime - startTime;
                    console.error(`截图失败，总耗时: ${duration.toFixed(2)}ms: ${screenshotResult.message || '未知错误'}`);
                    addMessage(`截图失败，总耗时: ${duration.toFixed(2)}ms: ${screenshotResult.message || '未知错误'}`, 'system');
                }
            } catch (error) {
                const endTime = performance.now();
                const duration = endTime - startTime;
                console.error(`截图时出错，总耗时: ${duration.toFixed(2)}ms:`, error);
                addMessage(`截图时出错，总耗时: ${duration.toFixed(2)}ms: ${error.message}`, 'system');
            }
        }
        
        // 使用YOLO分析图像 - 添加计时
        async function analyzeImageWithYOLO() {
            if (!capturedImage) {
                addMessage('请先截取屏幕', 'system');
                return;
            }
            
            const startTime = performance.now();
            console.log('开始调用YOLO服务...');
            addMessage('调用YOLO服务...', 'system');
            showLoading(true);
            
            try {
                // 使用配置文件中的 BASE_URL
                const response = await fetch(`${BASE_URL}/yolo/predict`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        image: capturedImage
                    })
                });
                
                const proxyResponseTime = performance.now();
                const proxyDuration = proxyResponseTime - startTime;
                console.log(`YOLO服务响应时间: ${proxyDuration.toFixed(2)}ms`);
                
                const predictionResult = await response.json();
                const proxyResultTime = performance.now();
                const proxyResultDuration = proxyResultTime - startTime;
                console.log(`YOLO服务结果解析时间: ${proxyResultDuration.toFixed(2)}ms`);
                
                if (predictionResult.status === 'success') {
                    // 显示处理后的图像
                    imagePreview.src = 'data:image/png;base64,' + predictionResult.processed_image;
                    capturedImage = imagePreview.src;
                    
                    // 保存检测数据
                    detectionData = predictionResult;
                    
                    // 显示检测结果
                    displayDetectionResults(predictionResult, 'YOLO');
                    
                    const endTime = performance.now();
                    const duration = endTime - startTime;
                    console.log(`YOLO图像分析完成，总耗时: ${duration.toFixed(2)}ms`);
                    addMessage(`YOLO图像分析完成，总耗时: ${duration.toFixed(2)}ms`, 'system');
                    analyzeImageBtn.disabled = false;
                    
                    // 如果检测到对象，启用点击按钮
                    if (predictionResult.detection_count > 0) {
                        clickDetectedBtn.disabled = false;
                    }
                } else {
                    const endTime = performance.now();
                    const duration = endTime - startTime;
                    console.error(`YOLO分析失败，总耗时: ${duration.toFixed(2)}ms: ${predictionResult.error || '未知错误'}`);
                    addMessage(`YOLO分析失败，总耗时: ${duration.toFixed(2)}ms: ${predictionResult.error || '未知错误'}`, 'system');
                }
            } catch (error) {
                const endTime = performance.now();
                const duration = endTime - startTime;
                console.error(`YOLO分析图像时出错，总耗时: ${duration.toFixed(2)}ms:`, error);
                addMessage(`YOLO分析图像时出错，总耗时: ${duration.toFixed(2)}ms: ${error.message}`, 'system');
            } finally {
                showLoading(false);
            }
        }
        
        // 使用GroundingDINO分析图像 - 添加计时
        async function analyzeImageWithGroundingDINO(prompt) {
            if (!capturedImage) {
                addMessage('请先截取屏幕', 'system');
                return;
            }
            
            if (!prompt) {
                addMessage('缺少检测目标描述', 'system');
                return;
            }
            
            const startTime = performance.now();
            console.log('开始调用GroundingDINO服务...');
            addMessage(`调用GroundingDINO服务，检测目标: ${prompt}`, 'system');
            showLoading(true);
            
            try {
                // 使用配置文件中的 BASE_URL
                const response = await fetch(`${BASE_URL}/groundingdino/predict`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        image: capturedImage.split(',')[1], // 移除 data:image/png;base64, 前缀
                        prompt: prompt
                    })
                });
                
                const proxyResponseTime = performance.now();
                const proxyDuration = proxyResponseTime - startTime;
                console.log(`GroundingDINO服务响应时间: ${proxyDuration.toFixed(2)}ms`);
                
                const predictionResult = await response.json();
                const proxyResultTime = performance.now();
                const proxyResultDuration = proxyResultTime - startTime;
                console.log(`GroundingDINO服务结果解析时间: ${proxyResultDuration.toFixed(2)}ms`);
                
                if (predictionResult.status === 'success') {
                    // 显示处理后的图像
                    imagePreview.src = 'data:image/png;base64,' + predictionResult.processed_image;
                    capturedImage = imagePreview.src;
                    
                    // 保存检测数据
                    detectionData = predictionResult;
                    
                    // 显示检测结果
                    displayDetectionResults(predictionResult, 'GroundingDINO');
                    
                    const endTime = performance.now();
                    const duration = endTime - startTime;
                    console.log(`GroundingDINO图像分析完成，总耗时: ${duration.toFixed(2)}ms`);
                    addMessage(`GroundingDINO图像分析完成，总耗时: ${duration.toFixed(2)}ms`, 'system');
                    analyzeImageBtn.disabled = false;
                    
                    // 如果检测到对象，启用点击按钮
                    if (predictionResult.detection_count > 0) {
                        clickDetectedBtn.disabled = false;
                    }
                } else {
                    const endTime = performance.now();
                    const duration = endTime - startTime;
                    console.error(`GroundingDINO分析失败，总耗时: ${duration.toFixed(2)}ms: ${predictionResult.error || '未知错误'}`);
                    addMessage(`GroundingDINO分析失败，总耗时: ${duration.toFixed(2)}ms: ${predictionResult.error || '未知错误'}`, 'system');
                }
            } catch (error) {
                const endTime = performance.now();
                const duration = endTime - startTime;
                console.error(`GroundingDINO分析图像时出错，总耗时: ${duration.toFixed(2)}ms:`, error);
                addMessage(`GroundingDINO分析图像时出错，总耗时: ${duration.toFixed(2)}ms: ${error.message}`, 'system');
            } finally {
                showLoading(false);
            }
        }
        
        // 显示检测结果
        function displayDetectionResults(data, modelType = 'Unknown') {
            detectionInfo.style.display = 'block';
            
            let html = `
                <p><strong>模型类型:</strong> ${modelType}</p>
                <p><strong>检测用时:</strong> ${data.processing_time.toFixed(2)} 秒</p>
                <p><strong>检测到对象数:</strong> ${data.detection_count}</p>
            `;
            
            if (data.detections && data.detections.length > 0) {
                html += '<h4>检测详情:</h4><ul>';
                data.detections.forEach(detection => {
                    html += `
                        <li>
                            ${detection.class_name} 
                            (置信度: ${(detection.confidence * 100).toFixed(1)}%)
                        </li>
                    `;
                });
                html += '</ul>';
            }
            
            detectionResults.innerHTML = html;
        }
        
        // 分析当前图像
        async function analyzeCurrentImage() {
            if (!capturedImage) {
                addMessage('请先截取屏幕', 'system');
                return;
            }
            
            await analyzeImageWithYOLO();
        }
        
        // 点击检测到的对象 - 添加计时
        async function clickDetectedObject() {
            if (!detectionData || !detectionData.detections || detectionData.detections.length === 0) {
                addMessage('没有检测到可点击的对象', 'system');
                return;
            }
            
            const startTime = performance.now();
            console.log('开始点击检测到的对象...');
            addMessage('正在点击检测到的对象...', 'system');
            showLoading(true);
            
            try {
                // 获取第一个检测到的对象的边界框中心点
                const firstDetection = detectionData.detections[0];
                const bbox = firstDetection.bbox;
                const centerX = (bbox[0] + bbox[2]) / 2;
                const centerY = (bbox[1] + bbox[3]) / 2;
                
                const calcTime = performance.now();
                const calcDuration = calcTime - startTime;
                console.log(`点击位置计算完成，耗时: ${calcDuration.toFixed(2)}ms`);
                
                // 使用配置文件中的 BASE_URL
                const response = await fetch(`${BASE_URL}/mouse/click`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        x: Math.round(centerX),
                        y: Math.round(centerY),
                        type: 'left',
                        clicks: 1
                    })
                });
                
                const proxyResponseTime = performance.now();
                const proxyDuration = proxyResponseTime - startTime;
                console.log(`鼠标点击响应时间: ${proxyDuration.toFixed(2)}ms`);
                
                const result = await response.json();
                const endTime = performance.now();
                const duration = endTime - startTime;
                
                if (result.status === 'success') {
                    console.log(`点击操作完成，总耗时: ${duration.toFixed(2)}ms`);
                    addMessage(`已点击检测到的 ${firstDetection.class_name} (位置: ${Math.round(centerX)}, ${Math.round(centerY)})，总耗时: ${duration.toFixed(2)}ms`, 'system');
                } else {
                    console.error(`点击操作失败，总耗时: ${duration.toFixed(2)}ms: ${result.message || '未知错误'}`);
                    addMessage(`点击操作失败，总耗时: ${duration.toFixed(2)}ms: ${result.message || '未知错误'}`, 'system');
                }
            } catch (error) {
                const endTime = performance.now();
                const duration = endTime - startTime;
                console.error(`点击操作时出错，总耗时: ${duration.toFixed(2)}ms:`, error);
                addMessage(`点击操作时出错，总耗时: ${duration.toFixed(2)}ms: ${error.message}`, 'system');
            } finally {
                showLoading(false);
            }
        }
        
        // 根据名称点击检测到的对象 - 添加计时
        async function clickDetectedObjectByName(objectName) {
            if (!detectionData || !detectionData.detections || detectionData.detections.length === 0) {
                return "没有检测到可点击的对象";
            }
            
            const startTime = performance.now();
            console.log(`开始点击对象: ${objectName || '默认第一个对象'}...`);
            
            let targetDetection = null;
            
            if (objectName) {
                // 查找指定名称的对象
                targetDetection = detectionData.detections.find(d => d.class_name === objectName);
                if (!targetDetection) {
                    const message = `未找到名为 "${objectName}" 的对象，将点击第一个检测到的对象`;
                    addMessage(message, 'system');
                    targetDetection = detectionData.detections[0];
                }
            } else {
                // 默认点击第一个对象
                targetDetection = detectionData.detections[0];
            }
            
            const findTime = performance.now();
            const findDuration = findTime - startTime;
            console.log(`对象查找完成，耗时: ${findDuration.toFixed(2)}ms`);
            
            try {
                const bbox = targetDetection.bbox;
                const centerX = (bbox[0] + bbox[2]) / 2;
                const centerY = (bbox[1] + bbox[3]) / 2;
                
                const calcTime = performance.now();
                const calcDuration = calcTime - startTime;
                console.log(`点击位置计算完成，耗时: ${calcDuration.toFixed(2)}ms`);
                
                // 使用配置文件中的 BASE_URL
                const response = await fetch(`${BASE_URL}/mouse/click`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        x: Math.round(centerX),
                        y: Math.round(centerY),
                        type: 'left',
                        clicks: 1
                    })
                });
                
                const proxyResponseTime = performance.now();
                const proxyDuration = proxyResponseTime - startTime;
                console.log(`鼠标点击响应时间: ${proxyDuration.toFixed(2)}ms`);
                
                const result = await response.json();
                const endTime = performance.now();
                const duration = endTime - startTime;
                
                if (result.status === 'success') {
                    const successMessage = `已点击 ${targetDetection.class_name} (位置: ${Math.round(centerX)}, ${Math.round(centerY)})，总耗时: ${duration.toFixed(2)}ms`;
                    console.log(successMessage);
                    return successMessage;
                } else {
                    const errorMessage = `点击操作失败: ${result.message || '未知错误'}，总耗时: ${duration.toFixed(2)}ms`;
                    console.error(errorMessage);
                    return errorMessage;
                }
            } catch (error) {
                const endTime = performance.now();
                const duration = endTime - startTime;
                console.error(`点击操作时出错，总耗时: ${duration.toFixed(2)}ms:`, error);
                return `点击操作时出错: ${error.message}，总耗时: ${duration.toFixed(2)}ms`;
            }
        }
        
        // 解析工具调用
        function parseToolCalls(response) {
            // 匹配工具调用的正则表达式
            const toolCallRegex = /<tool_call>(.*?)<\/tool_call>/g;
            const matches = [];
            let match;
            
            while ((match = toolCallRegex.exec(response)) !== null) {
                try {
                    // 尝试解析为JSON格式
                    const toolCall = JSON.parse(match[1]);
                    matches.push(toolCall);
                } catch (e) {
                    // 如果不是JSON格式，尝试解析为函数调用格式
                    const funcMatch = match[1].match(/(\w+)\((.*)\)/);
                    if (funcMatch) {
                        const toolName = funcMatch[1];
                        const argsStr = funcMatch[2];
                        const args = {};
                        
                        // 解析参数
                        if (argsStr) {
                            argsStr.split(',').forEach(arg => {
                                const [key, value] = arg.split('=');
                                if (key && value) {
                                    args[key.trim()] = value.trim().replace(/["']/g, '');
                                }
                            });
                        }
                        
                        matches.push({
                            name: toolName,
                            arguments: args
                        });
                    }
                }
            }
            
            return matches;
        }
        
        // 执行工具调用
        async function executeToolCalls(toolCalls) {
            const results = [];
            
            for (const toolCall of toolCalls) {
                try {
                    switch (toolCall.name) {
                        case 'capture_screen':
                            await captureScreen();
                            results.push({
                                name: 'capture_screen',
                                result: "屏幕截图已完成"
                            });
                            break;
                            
                        case 'analyze_image_with_yolo':
                            await analyzeImageWithYOLO();
                            if (detectionData && detectionData.detections) {
                                let detectionInfo = `使用YOLO检测到 ${detectionData.detection_count} 个对象: `;
                                detectionInfo += detectionData.detections.map(d => d.class_name).join(', ');
                                results.push({
                                    name: 'analyze_image_with_yolo',
                                    result: detectionInfo
                                });
                            } else {
                                results.push({
                                    name: 'analyze_image_with_yolo',
                                    result: "图像分析完成，未检测到对象"
                                });
                            }
                            break;
                            
                        case 'analyze_image_with_groundingdino':
                            const prompt = toolCall.arguments.prompt;
                            await analyzeImageWithGroundingDINO(prompt);
                            if (detectionData && detectionData.detections) {
                                let detectionInfo = `使用GroundingDINO检测到 ${detectionData.detection_count} 个对象: `;
                                detectionInfo += detectionData.detections.map(d => d.class_name).join(', ');
                                results.push({
                                    name: 'analyze_image_with_groundingdino',
                                    result: detectionInfo
                                });
                            } else {
                                results.push({
                                    name: 'analyze_image_with_groundingdino',
                                    result: "图像分析完成，未检测到对象"
                                });
                            }
                            break;
                            
                        case 'click_detected_object':
                            const objectName = toolCall.arguments.object_name;
                            const clickResult = await clickDetectedObjectByName(objectName);
                            results.push({
                                name: 'click_detected_object',
                                result: clickResult
                            });
                            break;
                            
                        default:
                            results.push({
                                name: toolCall.name,
                                result: `未知工具: ${toolCall.name}`
                            });
                    }
                } catch (error) {
                    results.push({
                        name: toolCall.name,
                        result: `执行工具 ${toolCall.name} 时出错: ${error.message}`
                    });
                }
            }
            
            return results;
        }
        
        // 发送消息 - 添加计时
        async function sendMessage() {
            const message = messageInput.value.trim();
            if (!message) return;
            
            const startTime = performance.now();
            console.log('开始发送消息...');
            addMessage(message, 'user');
            messageInput.value = '';
            
            // 将用户消息添加到对话历史
            conversationHistory.push({
                role: "user",
                content: message
            });
            
            showLoading(true);
            
            try {
                // 使用配置文件中的 BASE_URL
                const response = await fetch(`${BASE_URL}/chat`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        model: "deepseek-chat",
                        messages: conversationHistory,
                        temperature: 0.7
                    })
                });
                
                const aiResponseTime = performance.now();
                const aiDuration = aiResponseTime - startTime;
                console.log(`AI响应时间: ${aiDuration.toFixed(2)}ms`);
                
                if (!response.ok) {
                    throw new Error(`API请求失败: ${response.status}`);
                }
                
                const data = await response.json();
                const dataParseTime = performance.now();
                const dataParseDuration = dataParseTime - startTime;
                console.log(`AI响应解析时间: ${dataParseDuration.toFixed(2)}ms`);
                
                const aiResponse = data.choices[0].message.content;
                
                // 将AI响应添加到对话历史
                conversationHistory.push({
                    role: "assistant",
                    content: aiResponse
                });
                
                // 检查是否有工具调用
                const toolCalls = parseToolCalls(aiResponse);
                
                if (toolCalls.length > 0) {
                    addMessage(aiResponse, 'assistant');
                    
                    // 执行工具调用
                    showLoading(true);
                    const results = await executeToolCalls(toolCalls);
                    showLoading(false);
                    
                    // 将结果添加到消息中
                    let finalResponse = "工具调用结果:\n";
                    results.forEach((result, index) => {
                        finalResponse += `${index + 1}. ${result.name}: ${result.result}\n`;
                    });
                    
                    const endTime = performance.now();
                    const duration = endTime - startTime;
                    console.log(`工具调用完成，总耗时: ${duration.toFixed(2)}ms`);
                    addMessage(finalResponse, 'assistant');
                    
                    // 将工具调用结果也添加到对话历史中
                    conversationHistory.push({
                        role: "assistant",
                        content: finalResponse
                    });
                } else {
                    const endTime = performance.now();
                    const duration = endTime - startTime;
                    console.log(`消息发送完成，总耗时: ${duration.toFixed(2)}ms`);
                    addMessage(aiResponse, 'assistant');
                }
                
                // 限制对话历史长度，避免过长
                if (conversationHistory.length > 20) {
                    // 保留系统消息和最近的19条消息
                    conversationHistory = [conversationHistory[0], ...conversationHistory.slice(-19)];
                }
            } catch (error) {
                const endTime = performance.now();
                const duration = endTime - startTime;
                console.error(`发送消息时出错，总耗时: ${duration.toFixed(2)}ms:`, error);
                addMessage(`发送消息时出错，总耗时: ${duration.toFixed(2)}ms: ${error.message}`, 'system');
            } finally {
                showLoading(false);
            }
        }
        
        // 重置所有
        function resetAll() {
            // 重置图像和检测数据
            capturedImage = null;
            detectionData = null;
            imagePreviewContainer.style.display = 'none';
            detectionInfo.style.display = 'none';
            
            // 重置按钮状态
            analyzeBtn.disabled = true;
            analyzeImageBtn.disabled = true;
            clickDetectedBtn.disabled = true;
            
            // 重置对话历史，只保留系统消息
            conversationHistory = [conversationHistory[0]];
            
            addMessage('已重置所有内容', 'system');
        }
        
        // 添加消息到显示区域
        function addMessage(text, type) {
            const msgDiv = document.createElement('div');
            msgDiv.className = `message ${type}`;
            msgDiv.innerHTML = `<strong>${type === 'user' ? '用户' : type === 'assistant' ? 'AI助手' : '系统'} [${new Date().toLocaleString()}]</strong><br>${text}`;
            messagesDiv.appendChild(msgDiv);
            messagesDiv.scrollTop = messagesDiv.scrollHeight;
        }
        
        // 显示/隐藏加载指示器
        function showLoading(show) {
            loadingIndicator.style.display = show ? 'block' : 'none';
        }
        
        // 页面加载完成后的初始化
        document.addEventListener('DOMContentLoaded', function() {
            addMessage('AI终端已就绪', 'system');
        });
    </script>
</body>
</html>